package com.normal.zbase.impl.event

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.coroutineScope
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.lifecycle.viewModelScope
import com.normal.zbase.impl.base.BaseActivity
import com.normal.zbase.impl.base.BaseVM
import com.normal.zbase.impl.exceptions.CloudException
import com.normal.zbase.impl.tools.obj.LoadingObj
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch


/**
 * 三疯
 * *************************
 *
 * *************************
 */
object EventUtils {
    private var _eventFlow = MutableSharedFlow<EventBean>()
    private var eventFlow: SharedFlow<EventBean> = _eventFlow

    suspend fun sendEvent(eventBean: EventBean) {
        _eventFlow.emit(eventBean)
//        eventFlow.onStart {
//            logger.info("onStart")
//        }.onCompletion {
//            logger.info("onCompletion")
//            emit(eventBean)
//        }.catch {
//
//        }
    }

    fun subscriber(
        type: String,
        lifecycle: Lifecycle,
        callback: (EventBean) -> Unit
    ) {
        lifecycle.coroutineScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.CREATED) {
                eventFlow.filter {
                    it.type == type
                }.collect {
                    callback.invoke(it)
                }
            }
        }

    }
}